package cn.mystylefree.config;

import cn.mystylefree.io.Resources;
import cn.mystylefree.po.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2022/06/14 20:45
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    /**
     * 在调用到时候就会执行无参构造
     */
    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 对将配置文件使用dom4j进行解析，封装Configuration的方法
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document read = new SAXReader().read(inputStream);
        /*<configuration>根对象*/
        //数据源的解析
        Element rootElement = read.getRootElement();
        //表示 property 在任意位置都能获取到 一个property就是一个元素
        List<Element> list = rootElement.selectNodes("//property");
        //<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        //mapper.xml解析
        /*@step1 获取路径 拿到路径 字节流 dom4j*/
        //<mapper resource="userMapper.xml"></mapper>
        List<Element> elements = rootElement.selectNodes("//mapper");
        for (Element element : elements) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }
}
